package com.example.night.service.ApiService;

import com.example.night.data.Influencer.InfluencerPackage;
import com.example.night.data.InfluencerCoins.InfluencerCoins;
import com.example.night.data.InfluencerCoins.MonthlyInfluencerStats;
import com.example.night.data.InfluencerCoins.WithdrawRecord;
import com.example.night.service.MysqlService.InfluencerCoinsMysqlService;
import com.example.night.service.MysqlService.MonthlyInfluencerStatsMysqlService;
import com.example.night.service.MysqlService.WithdrawRecordMysqlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class InfluencerCoinsService {

    private final InfluencerService influencerService;
    private final MonthlyInfluencerStatsMysqlService monthlyStatsService;
    private final WithdrawRecordMysqlService withdrawRecordService;
    private final InfluencerCoinsMysqlService influencerCoinsService;

    private List<InfluencerCoins> influencerCoinsList = new ArrayList<>();

    public InfluencerCoinsService(InfluencerService influencerService,
                                  MonthlyInfluencerStatsMysqlService monthlyStatsService,
                                  WithdrawRecordMysqlService withdrawRecordService, InfluencerCoinsMysqlService influencerCoinsService) {
        this.influencerService = influencerService;
        this.monthlyStatsService = monthlyStatsService;
        this.withdrawRecordService = withdrawRecordService;
        this.influencerCoinsService = influencerCoinsService;
    }

    /**
     * 获取所有注册达人，并计算总金币、订单数、GMV、佣金、服务费、提现记录
     */
    public List<InfluencerCoins> getRegisteredInfluencersWithStats() {
        List<InfluencerPackage> registeredInfluencers = influencerService.getRegisteredInfluencers();
        List<InfluencerCoins> updatedInfluencerList = new ArrayList<>();

        for (InfluencerPackage influencer : registeredInfluencers) {
            String promoteId = influencer.getPromoteId();

            // 获取达人所有月份的统计数据
            List<MonthlyInfluencerStats> monthlyStats = monthlyStatsService.getAllStatsByPromoteId(promoteId);

            // 计算总金币、订单数、GMV、佣金、服务费
            int totalCoins = 0;
            int totalOrders = 0;
            BigDecimal totalGMV = BigDecimal.ZERO;
            BigDecimal totalCommission = BigDecimal.ZERO;
            BigDecimal totalServiceMoney = BigDecimal.ZERO;

            for (MonthlyInfluencerStats stats : monthlyStats) {
                totalCoins += stats.getCoins();
                totalOrders += stats.getTotalOrders();
                totalGMV = totalGMV.add(stats.getTotalGMV());
                totalCommission = totalCommission.add(stats.getTotalCommission());
                totalServiceMoney = totalServiceMoney.add(stats.getLeaderSysServiceMoney());
            }

            // **获取提现记录**
            List<WithdrawRecord> withdrawRecords = withdrawRecordService.getWithdrawRecordsByPromoteId(promoteId);
            int withdrawnCoins = 0;
            int pendingWithdrawCoins = 0;

            for (WithdrawRecord record : withdrawRecords) {
                if (record.getStatus() == WithdrawRecord.WithdrawStatus.COMPLETED) {
                    withdrawnCoins += record.getWithdrawCoins();  // 已提现金币
                } else if (record.getStatus() == WithdrawRecord.WithdrawStatus.PENDING) {
                    pendingWithdrawCoins += record.getWithdrawCoins();  // 申请中的金币
                }
            }

            // **填充达人信息**
            InfluencerCoins influencerCoins = new InfluencerCoins();
            influencerCoins.setPromoteId(promoteId);
            influencerCoins.setPromoteName(influencer.getPromoteName());
            influencerCoins.setPhone(influencer.getPhone());
            influencerCoins.setName(influencer.getName());
            influencerCoins.setCoins(totalCoins);
            influencerCoins.setTotalOrders(totalOrders);
            influencerCoins.setTotalGMV(totalGMV);
            influencerCoins.setTotalCommission(totalCommission);
            influencerCoins.setLeaderSysServiceMoney(totalServiceMoney);
            influencerCoins.setWithdrawnCoins(withdrawnCoins);
            influencerCoins.setPendingWithdrawCoins(pendingWithdrawCoins);


            // 存入列表
            updatedInfluencerList.add(influencerCoins);
        }
        influencerCoinsService.addOrUpdateInfluencerCoinsBatch(updatedInfluencerList);
        return updatedInfluencerList;
    }
    /**
     * 申请提现金币
     * @param promoteId 达人ID
     * @param withdrawCoins 申请提现的金币数量
     * @return 是否申请成功
     */
    public boolean applyForWithdraw(String promoteId, int withdrawCoins) {
        Optional<InfluencerCoins> influencerCoinsOpt = influencerCoinsService.getByPromoteId(promoteId);

        if (influencerCoinsOpt.isPresent()) {
            InfluencerCoins influencerCoins = influencerCoinsOpt.get();

            // **检查金币是否足够**
            if (influencerCoins.getCoins() < withdrawCoins) {
                log.warn("达人[{}]金币不足，无法申请提现", promoteId);
                return false;
            }

            // **更新数据**
            influencerCoins.setCoins(influencerCoins.getCoins() - withdrawCoins); // 扣除金币
            influencerCoins.setPendingWithdrawCoins(influencerCoins.getPendingWithdrawCoins() + withdrawCoins); // 增加申请提现金币

            // **保存更新**
            influencerCoinsService.addOrUpdateInfluencerCoins(influencerCoins);
            log.info("达人[{}]成功申请提现{}金币", promoteId, withdrawCoins);
            return true;
        } else {
            log.warn("达人[{}]不存在，无法申请提现", promoteId);
            return false;
        }
    }

}
